
const LINENUM = 9;
const LINENUM_RADOM = 12;
var RATE = [0, 0];

var fs = require('fs');
var path = require('path');

var filterFils = [];
var filterDirs = [];

//cocos引擎自身存在的方法名：
var filtFunctionName = require("./core_cocos.js").filtFunctionName;
//项目特有过滤方法名：
filtFunctionName = filtFunctionName.concat(["setVisible", "dispose", "destory", "release",
	"constructor", "createInstance", "onConstruct", "getItem", "setItem", "fontSize", "fontBorderSize", "parseFloat", "underLine", "getUTCHours", "getUTCMinutes", "getUTCSeconds", "getHours", "getMinutes", "getSeconds", "form", "send", "forEach", "Init", "Update", "removeItem", "clear", "Global", "getMailList", "finished", "login", "getSetting", "authorize", "getUserInfo", "getSystemInfoSync", "showToast", "hideToast", "createBannerAd", "vibrateShort", "createUserInfoButton", "getServetTime", "getServetTime1", "setMyTask", "getUnionid", "getGiftList", "getStoreList", "getBackpack", "setUserEquipmentJson", "addCoin", "Bonus", "getBuyEquip", "getDropPoolList", "getBarrierList", "getSkillPoolList", "rankingList", "getRentequipList", "getAdvrewardList", "getMailList", "setMyMail", "getUserFriend", "EmailDetails", "getUserProfit", "getGiftCodeReward", "setExchangeDiamond", "rankingMy", "getBoxFloors",
	"moveSpeed", "setUserinfoPost"
]);
// node changejs2.js /Users/zhixiang/Documents/proj/minigame-btxd/client_btxd_z/build/wechatgame/src/project.41ad2.js '' BaoShi '/Users/zhixiang/Documents/proj/minigame-btxd/client_btxd_z/build/wechatgame/res/import'
var arguments = process.argv.splice(2);
var path2 = "xxxxxx.js";
if (arguments.length > 1) {
	path2 = arguments[1];
}
var classExpString = arguments[2];
console.log(arguments, arguments);

if (arguments.length > 3) { //方法名在皮肤里面绑定的，故修改方法名也要修改json
	var skinFileList = {};
	var skinFileListNew = {};
	fileDisplay(arguments[3]);
}
var jsurl = arguments[0];
//md5Code(jsurl);
setTimeout(() => { md5Code(jsurl); }, 2000)


function fileDisplay(filePath) {
	//根据文件路径读取文件，返回文件列表
	fs.readdir(filePath, function (err, files) {
		if (err) {
			console.warn(err)
		} else {
			//遍历读取到的文件列表
			files.forEach(function (filename) {
				//获取当前文件的绝对路径
				var filedir = path.join(filePath, filename);
				//根据文件路径获取文件信息，返回一个fs.Stats对象
				fs.stat(filedir, function (eror, stats) {
					if (eror) {
						console.warn('获取文件stats失败');
					} else {
						var isFile = stats.isFile();//是文件
						var isDir = stats.isDirectory();//是文件夹
						if (isFile) {
							//console.log(filename,filedir);
							let onlyName = filename.split(".")[0];
							if (filename.indexOf(".json") != -1 && filterFils.indexOf(filename) == -1) {
								//console.log(filedir);
								skinFileList[filedir] = skinFileListNew[filedir] = fs.readFileSync(filedir, { encoding: "utf8" });
							}
						}
						if (isDir) {
							if (!filterDirs || filterDirs.indexOf(filename) == -1) {
								fileDisplay(filedir);//递归，如果是文件夹，就继续遍历该文件夹下面的文件
							}
						}
					}
				})
			});
		}
	});
}


function md5Code(phppath) {

	console.log("执行文件：" + phppath);
	let codeContent = fs.readFileSync(phppath, { encoding: "utf8" });
	//console.log(codeContent);


	//let jsFile2 = fs.readFileSync(path2, { encoding: "utf8" });

	/** 格式化代码 ******************/
	var js_parse = require("./js_parse.js");
	codeContent = js_parse.js_beautify(codeContent, 4, ' ');


	//====修改私有方法名==================================================================
	//【修改代码】
	///let arr = codeContent.match(/            \s*(\w+)\(\) \{/g); //寻找类方法 的方法名
	let arr = codeContent.match(/\.prototype\.\s*(\w+) = function\(/g); //寻找类方法 的方法名
	arr = [...new Set(arr)];//去除重复的字符串
	arr = arr.map(function (value) {
		///return value.replace("            ", "").replace("() {", "");
		return value.replace(".prototype.", "").replace(" = function(", "");
	});

	//静态方法
	///let arr2 = codeContent.match(/static \s*(\w+)\(/g); 
	let arr2 = codeContent.match(/e\.\s*(\w+) = function\(/g);
	arr2 = [...new Set(arr2)];//去除重复的字符串
	arr2 = arr2.map(function (value) {
		///return value.replace("static ", "").replace("(", "");
		return value.replace("e.", "").replace(" = function(", "");
	});

	arr = arr.concat(arr2);
	arr = [...new Set(arr)];//去除重复的字符串


	arr = arr.filter(function (value) {
		return filtFunctionName.indexOf(value) < 0;
	});

	console.log(arr);
	if (arr) {
		var funExp, result, newName, regExp;
		for (var i = 0; i < arr.length; i++) {
			//【修改代码】
			if (arr[i].indexOf("_") > -1 || arr[i].length < 5) continue;
			if (arr[i].length < 4) continue;
			if (arr[i].indexOf("index") > -1) continue; //项目特殊规则，方法名拼接
			if (arr[i].toLocaleLowerCase() == arr[i]) continue; //纯小写的，有可能是 ui变量名
			if (codeContent.match(new RegExp("\\b" + arr[i] + "\\.", 'g'))) continue; // 过滤ui对象 xxx.visible

			if (codeContent.match(new RegExp("\\bwx\\." + arr[i], 'g'))) continue; //wx.xxxx 微信的方法
			if (codeContent.match(new RegExp("\\bJSON\\." + arr[i], 'g'))) continue; //JSON.xxxx 微信的方法
			if (codeContent.match(new RegExp("\\bBase64\\." + arr[i], 'g'))) continue; //Base64.xxxx 微信的方法
			if (codeContent.match(new RegExp("\\bBase64Util\\." + arr[i], 'g'))) continue; //Base64.xxxx
			if (codeContent.match(new RegExp("\\bJSONParseClass\\." + arr[i], 'g'))) continue; //JSONParseClass.xxx
			if (codeContent.match(new RegExp("\\$" + arr[i], 'g'))) continue; //可能存在的引擎私有方法的写法

			newName = encryptName(arr[i], classExpString);
			console.log("newName:", arr[i], newName);
			regExp = new RegExp("\\b" + arr[i] + "\\b", 'g'); //this.funname(
			codeContent = codeContent.replace(regExp, newName + "");

			// jsFile2 = jsFile2.replace(regExp, newName + "");

			if (skinFileListNew) {
				for (var jj in skinFileListNew) {
					//console.log("-----",jj);
					skinFileListNew[jj] = skinFileListNew[jj].replace(regExp, newName);
				}
			}
		}
	}
	//console.log(codeContent);

	for (var jj in skinFileListNew) {
		if (skinFileList[jj] != skinFileListNew[jj]) {
			fs.writeFileSync(jj, skinFileListNew[jj], { encoding: "utf8" });
			console.log("json-----" + jj);
		}
	}

	/** 压缩代码 ******************/
	codeContent = js_parse.jsmin("", codeContent, 2);

	fs.writeFileSync(phppath, codeContent, { encoding: "utf8" });
	console.log("执行完成！--" + phppath);
	//fs.writeFileSync(path2, jsFile2, { encoding: "utf8" });
	//console.log("执行完成！--" + path2);
}

function encryptName(name, key) {
	var newname = name.split("");
	for (var i = 0; i < name.length; i++) {
		let code = name.charCodeAt(i) % 20;
		if (i < key.length) {
			let code2 = key.charCodeAt(i);
			let word = key.charAt(i);
			if ((code2 + code <= 122 && code2 + code >= 97) || (code2 + code <= 90)) {
				let newCode = code2 + code;
				if (newCode > 122) {
					newCode = newCode - 26;
				}
				word = String.fromCharCode(newCode);

				// 引入随机因素
				let randomCode = Math.floor(Math.random() * 10); // 生成0到25之间的随机数
				let randomWord = String.fromCharCode(97 + randomCode); // 将随机数转换为对应的小写字母
				word += randomWord;
			} else {
				word = '';
			}
			newname[i] = newname[i] + word;
		}
	}
	return newname.join("").replace(/[^A-Za-z]/g, '');
}

function jiaMiKey(name, key) {
	var newname = name.split("");
	for (var i = 0; i < name.length; i++) {
		let code = name.charCodeAt(i) % 20;
		if (i < key.length) {
			let code2 = key.charCodeAt(i);
			let word = key.charAt(i);
			if ((code2 + code <= 122 && code2 + code >= 97) || (code2 + code <= 90)) {
				let newCode = code2 + code;
				if (newCode > 122) {
					newCode = newCode - 26;
				}
				word = String.fromCharCode(newCode);
			} else {
				word = '';
			}
			newname[i] = newname[i] + word;
		}
	}
	return newname.join("").replace(/[^A-Za-z]/g, '');
}

function jieMiKey(name, key) {
	var newname = name.split("");//[x1,a,x2,b,x3,c,x4,d,...]
	for (var i = key.length; i > 0; i--) {
		newname.splice(i * 2 - 1, 1);
	}
	return newname.join("");
}


function getLeftSpace(str) {
	if (!str) return 0;
	let num = str.length - lTrim(str).length;
	return num;
}

function getAddSpace(str) {
	if (!str) return "";
	let num = str.length - lTrim(str).length;
	let formatStr = Trim(str, "g");
	if (formatStr == "}")
		num += 4;
	let space = "";
	while (num > 0) {
		space += " ";
		num--;
	}
	return space;
}
function Trim(str, is_global) {
	//console.log("==", str)
	str = String(str);
	var result;
	result = str.replace(/(^\s+)|(\s+$)/g, "");
	if (is_global && is_global.toLowerCase() == "g") {
		result = result.replace(/\s/g, "");
	}
	return result;
}
function lTrim(str) {
	str = String(str);
	var result = str.replace(/(^\s+)/g, "");
	return result;
}
